package org.suze.redis.connection;

import org.suze.redis.protocol.Protocol;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @description:
 * @Date : 2018/9/21 下午8:42
 * @Author : 石冬冬-Seig Heil(dongdong.shi@mljr.com)
 */
public class Connection {

    private Socket socket;
    private String host;
    private  int port;
    private OutputStream outputStream;
    private InputStream inputStream;

    public Connection(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connection(){
        try {
            socket = new Socket(host,port);
            socket.setReuseAddress(true);
            // Will monitor the TCP connection is
            socket.setKeepAlive(true);
            // valid
            // Socket buffer Whetherclosed, to
            socket.setTcpNoDelay(true);
            // ensure timely delivery of data
            // Control calls close () method,
            socket.setSoLinger(true, 0);
            outputStream = socket.getOutputStream();
            inputStream = socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean isConnected() {
        return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected()
                && !socket.isInputShutdown() && !socket.isOutputShutdown();
    }

    public Connection sendCommand(Protocol.Command command, byte[]...args){
        connection();
        Protocol.sendCommand(outputStream,command,args);
        return this;
    }


    public String getStatusCodeReply(){
        byte[] bytes = new byte[1024];
        try {
            socket.getInputStream().read(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(bytes);
    }
}
